// pages/health/calendar.js
const app = getApp();
const themeManager = require('../../utils/theme-manager');
const storage = require('../../utils/storage');

Page({
  data: {
    // 主题相关
    currentTheme: 'pink',
    themeColors: {},
    
    // 日历数据
    currentYear: 2024,
    currentMonth: 1,
    calendarDays: [],
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    
    // 生理期数据
    cycleData: {
      lastPeriodDate: null,
      cycleLength: 28,
      periodLength: 5,
      nextPeriodDate: null
    },
    
    // 记录数据
    healthRecords: {}, // 格式: { '2024-01-15': { symptoms: [], mood: '', energy: 80, notes: '' } }
    
    // 预测数据
    predictions: {
      periodDates: [], // 预测的月经日期
      ovulationDates: [], // 预测的排卵日期
      fertileDates: [] // 预测的易孕期日期
    },
    
    // 选中的日期
    selectedDate: '',
    selectedDateData: null,
    
    // UI状态
    showDateModal: false,
    showSettingsModal: false,
    showLegendModal: false,
    
    // 日期类型图例
    legend: [
      { type: 'period', name: '月经期', color: '#FF6B6B', icon: '🌙' },
      { type: 'ovulation', name: '排卵日', color: '#45B7D1', icon: '🌸' },
      { type: 'fertile', name: '易孕期', color: '#4ECDC4', icon: '🌱' },
      { type: 'recorded', name: '有记录', color: '#FFA07A', icon: '📝' },
      { type: 'today', name: '今天', color: '#FFD700', icon: '⭐' }
    ],
    
    // 症状选项
    symptoms: [
      { id: 'cramps', name: '痛经', icon: '🤕' },
      { id: 'bloating', name: '腹胀', icon: '🎈' },
      { id: 'headache', name: '头痛', icon: '😵' },
      { id: 'fatigue', name: '疲劳', icon: '😴' },
      { id: 'mood_swings', name: '情绪波动', icon: '😢' },
      { id: 'acne', name: '痘痘', icon: '😰' },
      { id: 'breast_tenderness', name: '乳房胀痛', icon: '💔' },
      { id: 'back_pain', name: '腰痛', icon: '🦴' }
    ],
    
    // 心情选项
    moods: [
      { id: 'happy', name: '开心', emoji: '😊', color: '#FFD700' },
      { id: 'calm', name: '平静', emoji: '😌', color: '#87CEEB' },
      { id: 'anxious', name: '焦虑', emoji: '😰', color: '#FFA500' },
      { id: 'sad', name: '难过', emoji: '😢', color: '#6495ED' },
      { id: 'angry', name: '愤怒', emoji: '😠', color: '#FF6347' },
      { id: 'tired', name: '疲惫', emoji: '😴', color: '#9370DB' }
    ],
    
    // 加载状态
    loading: true
  },

  onLoad(options) {
    this.initTheme();
    this.initCalendar();
    this.loadHealthData();
    this.calculatePredictions();
    this.generateCalendarDays();
    this.setData({ loading: false });
  },

  onShow() {
    this.refreshCalendar();
  },

  // 初始化主题
  initTheme() {
    const userInfo = app.globalData.userInfo || {};
    const theme = userInfo.role === 'male' ? 'gold' : 'pink';
    const colors = themeManager.getThemeColors(theme);
    
    this.setData({
      currentTheme: theme,
      themeColors: colors
    });
  },

  // 初始化日历
  initCalendar() {
    const now = new Date();
    this.setData({
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1
    });
  },

  // 加载健康数据
  loadHealthData() {
    const cycleData = storage.get('cycleData') || this.data.cycleData;
    const healthRecords = storage.get('healthRecords') || {};
    
    this.setData({
      cycleData,
      healthRecords
    });
  },

  // 计算预测数据
  calculatePredictions() {
    const { cycleData } = this.data;
    
    if (!cycleData.lastPeriodDate) {
      return;
    }
    
    const lastPeriod = new Date(cycleData.lastPeriodDate);
    const predictions = {
      periodDates: [],
      ovulationDates: [],
      fertileDates: []
    };
    
    // 预测未来6个月的周期
    for (let i = 0; i < 6; i++) {
      const cycleStart = new Date(lastPeriod);
      cycleStart.setDate(cycleStart.getDate() + (cycleData.cycleLength * i));
      
      // 月经期
      for (let j = 0; j < cycleData.periodLength; j++) {
        const periodDate = new Date(cycleStart);
        periodDate.setDate(periodDate.getDate() + j);
        predictions.periodDates.push(periodDate.toISOString().split('T')[0]);
      }
      
      // 排卵日 (周期第14天)
      const ovulationDate = new Date(cycleStart);
      ovulationDate.setDate(ovulationDate.getDate() + 13);
      predictions.ovulationDates.push(ovulationDate.toISOString().split('T')[0]);
      
      // 易孕期 (排卵日前5天到后1天)
      for (let k = -5; k <= 1; k++) {
        const fertileDate = new Date(ovulationDate);
        fertileDate.setDate(fertileDate.getDate() + k);
        predictions.fertileDates.push(fertileDate.toISOString().split('T')[0]);
      }
    }
    
    this.setData({ predictions });
  },

  // 生成日历天数
  generateCalendarDays() {
    const { currentYear, currentMonth } = this.data;
    const firstDay = new Date(currentYear, currentMonth - 1, 1);
    const lastDay = new Date(currentYear, currentMonth, 0);
    const daysInMonth = lastDay.getDate();
    const startWeekDay = firstDay.getDay();
    
    const calendarDays = [];
    
    // 添加上个月的日期
    const prevMonth = currentMonth === 1 ? 12 : currentMonth - 1;
    const prevYear = currentMonth === 1 ? currentYear - 1 : currentYear;
    const prevMonthLastDay = new Date(prevYear, prevMonth, 0).getDate();
    
    for (let i = startWeekDay - 1; i >= 0; i--) {
      const day = prevMonthLastDay - i;
      const dateStr = `${prevYear}-${String(prevMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      calendarDays.push({
        day,
        dateStr,
        isCurrentMonth: false,
        isToday: false,
        ...this.getDayInfo(dateStr)
      });
    }
    
    // 添加当前月的日期
    const today = new Date().toISOString().split('T')[0];
    for (let day = 1; day <= daysInMonth; day++) {
      const dateStr = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      const isToday = dateStr === today;
      
      calendarDays.push({
        day,
        dateStr,
        isCurrentMonth: true,
        isToday,
        ...this.getDayInfo(dateStr)
      });
    }
    
    // 添加下个月的日期
    const nextMonth = currentMonth === 12 ? 1 : currentMonth + 1;
    const nextYear = currentMonth === 12 ? currentYear + 1 : currentYear;
    const remainingDays = 42 - calendarDays.length; // 6行 * 7天
    
    for (let day = 1; day <= remainingDays; day++) {
      const dateStr = `${nextYear}-${String(nextMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      calendarDays.push({
        day,
        dateStr,
        isCurrentMonth: false,
        isToday: false,
        ...this.getDayInfo(dateStr)
      });
    }
    
    this.setData({ calendarDays });
  },

  // 获取日期信息
  getDayInfo(dateStr) {
    const { predictions, healthRecords } = this.data;
    
    const info = {
      isPeriod: predictions.periodDates.includes(dateStr),
      isOvulation: predictions.ovulationDates.includes(dateStr),
      isFertile: predictions.fertileDates.includes(dateStr),
      hasRecord: !!healthRecords[dateStr],
      symptoms: healthRecords[dateStr]?.symptoms || [],
      mood: healthRecords[dateStr]?.mood || '',
      energy: healthRecords[dateStr]?.energy || 0,
      notes: healthRecords[dateStr]?.notes || ''
    };
    
    return info;
  },

  // 刷新日历
  refreshCalendar() {
    this.loadHealthData();
    this.calculatePredictions();
    this.generateCalendarDays();
  },

  // 上一个月
  onPrevMonth() {
    let { currentYear, currentMonth } = this.data;
    
    if (currentMonth === 1) {
      currentYear--;
      currentMonth = 12;
    } else {
      currentMonth--;
    }
    
    this.setData({ currentYear, currentMonth });
    this.generateCalendarDays();
  },

  // 下一个月
  onNextMonth() {
    let { currentYear, currentMonth } = this.data;
    
    if (currentMonth === 12) {
      currentYear++;
      currentMonth = 1;
    } else {
      currentMonth++;
    }
    
    this.setData({ currentYear, currentMonth });
    this.generateCalendarDays();
  },

  // 回到今天
  onToday() {
    const now = new Date();
    this.setData({
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1
    });
    this.generateCalendarDays();
  },

  // 选择日期
  onSelectDate(e) {
    const { date } = e.currentTarget.dataset;
    const dayInfo = this.data.calendarDays.find(day => day.dateStr === date);
    
    this.setData({
      selectedDate: date,
      selectedDateData: dayInfo,
      showDateModal: true
    });
  },

  // 记录月经
  onRecordPeriod() {
    const { selectedDate } = this.data;
    
    wx.showModal({
      title: '记录月经',
      content: `确认${selectedDate}是月经日吗？`,
      success: (res) => {
        if (res.confirm) {
          // 更新周期数据
          const cycleData = {
            ...this.data.cycleData,
            lastPeriodDate: selectedDate
          };
          
          this.setData({ cycleData });
          storage.set('cycleData', cycleData);
          
          // 重新计算预测
          this.calculatePredictions();
          this.generateCalendarDays();
          
          wx.showToast({
            title: '记录成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 选择症状
  onSelectSymptom(e) {
    const { symptom } = e.currentTarget.dataset;
    const { selectedDate, healthRecords } = this.data;
    
    const dateRecord = healthRecords[selectedDate] || { symptoms: [], mood: '', energy: 0, notes: '' };
    const symptoms = [...dateRecord.symptoms];
    
    const index = symptoms.indexOf(symptom);
    if (index > -1) {
      symptoms.splice(index, 1);
    } else {
      symptoms.push(symptom);
    }
    
    const updatedRecord = { ...dateRecord, symptoms };
    const updatedRecords = { ...healthRecords, [selectedDate]: updatedRecord };
    
    this.setData({
      healthRecords: updatedRecords,
      'selectedDateData.symptoms': symptoms,
      'selectedDateData.hasRecord': true
    });
    
    storage.set('healthRecords', updatedRecords);
  },

  // 选择心情
  onSelectMood(e) {
    const { mood } = e.currentTarget.dataset;
    const { selectedDate, healthRecords } = this.data;
    
    const dateRecord = healthRecords[selectedDate] || { symptoms: [], mood: '', energy: 0, notes: '' };
    const updatedRecord = { ...dateRecord, mood };
    const updatedRecords = { ...healthRecords, [selectedDate]: updatedRecord };
    
    this.setData({
      healthRecords: updatedRecords,
      'selectedDateData.mood': mood,
      'selectedDateData.hasRecord': true
    });
    
    storage.set('healthRecords', updatedRecords);
  },

  // 更新能量值
  onEnergyChange(e) {
    const energy = e.detail.value;
    const { selectedDate, healthRecords } = this.data;
    
    const dateRecord = healthRecords[selectedDate] || { symptoms: [], mood: '', energy: 0, notes: '' };
    const updatedRecord = { ...dateRecord, energy };
    const updatedRecords = { ...healthRecords, [selectedDate]: updatedRecord };
    
    this.setData({
      healthRecords: updatedRecords,
      'selectedDateData.energy': energy,
      'selectedDateData.hasRecord': true
    });
    
    storage.set('healthRecords', updatedRecords);
  },

  // 更新备注
  onNotesInput(e) {
    const notes = e.detail.value;
    const { selectedDate, healthRecords } = this.data;
    
    const dateRecord = healthRecords[selectedDate] || { symptoms: [], mood: '', energy: 0, notes: '' };
    const updatedRecord = { ...dateRecord, notes };
    const updatedRecords = { ...healthRecords, [selectedDate]: updatedRecord };
    
    this.setData({
      healthRecords: updatedRecords,
      'selectedDateData.notes': notes,
      'selectedDateData.hasRecord': true
    });
    
    storage.set('healthRecords', updatedRecords);
  },

  // 打开设置
  onOpenSettings() {
    this.setData({ showSettingsModal: true });
  },

  // 更新周期长度
  onCycleLengthChange(e) {
    const cycleLength = parseInt(e.detail.value);
    const cycleData = { ...this.data.cycleData, cycleLength };
    
    this.setData({ cycleData });
    storage.set('cycleData', cycleData);
    
    // 重新计算预测
    this.calculatePredictions();
    this.generateCalendarDays();
  },

  // 更新经期长度
  onPeriodLengthChange(e) {
    const periodLength = parseInt(e.detail.value);
    const cycleData = { ...this.data.cycleData, periodLength };
    
    this.setData({ cycleData });
    storage.set('cycleData', cycleData);
    
    // 重新计算预测
    this.calculatePredictions();
    this.generateCalendarDays();
  },

  // 显示图例
  onShowLegend() {
    this.setData({ showLegendModal: true });
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showDateModal: false,
      showSettingsModal: false,
      showLegendModal: false
    });
  },

  // 获取日期显示类型
  getDayClass(day) {
    const classes = ['calendar-day'];
    
    if (!day.isCurrentMonth) {
      classes.push('other-month');
    }
    
    if (day.isToday) {
      classes.push('today');
    }
    
    if (day.isPeriod) {
      classes.push('period-day');
    } else if (day.isOvulation) {
      classes.push('ovulation-day');
    } else if (day.isFertile) {
      classes.push('fertile-day');
    }
    
    if (day.hasRecord) {
      classes.push('recorded-day');
    }
    
    return classes.join(' ');
  },

  // 获取月份名称
  getMonthName(month) {
    const months = [
      '一月', '二月', '三月', '四月', '五月', '六月',
      '七月', '八月', '九月', '十月', '十一月', '十二月'
    ];
    return months[month - 1];
  },

  // 分享日历
  onShareCalendar() {
    return {
      title: '我的生理期日历',
      path: '/pages/health/calendar',
      imageUrl: '/images/calendar-share.png'
    };
  },

  // 获取心情表情的辅助方法
  getMoodEmoji(moodId) {
    if (!moodId) return '';
    const mood = this.data.moods.find(m => m.id === moodId);
    return mood ? mood.emoji : '';
  },

  onShareAppMessage() {
    return this.onShareCalendar();
  }
});